#ifndef __MY_SERVER__
#define __MY_SERVER__

#include <iostream>
#include <unistd.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
namespace wzh
{
    class udpserver
    {
    private:
        int _sock;
        uint16_t _port;
    public:
        udpserver(int port) : _port(port) 
        {}
        void initServer()
        {
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if(_sock < 0)
            {
                std::cout << "create socket fail\n";
                exit(-1);
            }
            std::cout << "create socket success\n";

            struct sockaddr_in addr;
            bzero(&addr, sizeof(addr));
            addr.sin_addr.s_addr = INADDR_ANY;
            addr.sin_family = AF_INET;
            addr.sin_port = htons(_port);
            // std::cout << addr.sin_port << std::endl;
            if(bind(_sock, (struct sockaddr*)&addr, sizeof(addr)) < 0)
            {
                perror("bind");
                exit(-1);
            }
            std::cout << "bind success\n";
        }
        void start()
        {
            while(1)
            {
                char buffer[1024];
                struct sockaddr_in cli;
                socklen_t len = sizeof(cli);
                int ret = recvfrom(_sock, buffer, sizeof(buffer), 0, (struct sockaddr*)&cli, &len);
                std::cout << "recv " << buffer << std::endl;
                if(ret > 0)
                {
                    int ret = sendto(_sock, buffer, sizeof(buffer), 0, (struct sockaddr*)&cli, len);
                    if(ret > 0)
                        std::cout << "send " << buffer << std::endl;
                }
                else if(ret == 0)
                {
                    std::cout << "communication fail\n";
                    break;
                }
                else
                {
                    std::cout << "recvfrom fail\n";
                    break;
                }
            }
        }
        ~udpserver()
        {

        }
    };  
}

#endif